<template>
  <div class="container">
    <Breadcrumb />
    <a-card class="data-card" v-if="dictTypeId == ''">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
          >
            <a-row :gutter="20">
              <a-col :span="5">
                <a-form-item field="dictName" label="字典名称">
                  <a-input
                    v-model="formModel.dictName"
                    placeholder="请输入字典名称"
                    allow-clear
                  />
                </a-form-item>
              </a-col>

              <a-col :span="4">
                <a-space :size="18">
                  <a-button @click="openAdd" type="primary">
                    <template #icon>
                      <icon-plus />
                    </template>
                    新增
                  </a-button>
                  <a-button @click="onPageChange(1)" type="primary">
                    <template #icon>
                      <icon-search />
                    </template>
                    搜索
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    重置
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-table
        row-key="id"
        :loading="loading"
        page-position="bottom"
        :pagination="pagination"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #option="{ record }">
          <a-space :size="18">
            <a-button @click="openEdit(record)" type="outline"> 编辑 </a-button>
            <a-button status="danger" @click="openDelete(record)">
              删除
            </a-button>
            <a-button type="primary" @click="gorouter(record)"> 查看 </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <a-modal
      v-model:visible="addShow"
      @cancel="handleCancel"
      :on-before-ok="handleCheck"
      :mask-closable="false"
      unmountOnClose
    >
      <template #title> 字典类型 </template>
      <a-form ref="addModel" :rules="rules" :model="addForm">
        <a-form-item field="dictName" label="字典名称">
          <a-input
            v-model="addForm.dictName"
            size="large"
            placeholder="请输入字典名称"
          />
        </a-form-item>
        <a-form-item field="dictType" label="字典类型">
          <a-input
            v-model="addForm.dictType"
            size="large"
            placeholder="请输入字典类型"
          />
        </a-form-item>
        <a-form-item field="remark" label="字典备注">
          <a-input
            v-model="addForm.remark"
            size="large"
            placeholder="请输入字典备注"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <dataXq
      v-if="dictTypeId != ''"
      :dictTypeId="dictTypeId"
      @child-event="handler3"
    />
  </div>
  <!-- 详情 -->
</template>

<script lang="ts" setup>
  import { computed, ref, reactive } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import {
    dictTypeList,
    addDictType,
    updateDictType,
    deleteDictType,
  } from '@/api/dict.ts';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import dataXq from '@/views/system/dict/data.vue';

  const { loading, setLoading } = useLoading(true);
  const dictTypeId = ref('');
  const handler3 = () => {
    dictTypeId.value = '';
  };
  const gorouter = (item) => {
    dictTypeId.value = item.dictTypeId;
  };

  const generateDataModel = () => {
    return {
      dictId: '',
      dictName: '',
      dictType: '',
      remark: '',
    };
  };
  const rules = {
    dictName: [
      {
        required: true,
        message: '请输入字典名称',
      },
    ],
    dictType: [
      {
        required: true,
        message: '请输入字典类型',
      },
    ],
  };
  const addForm = ref(generateDataModel());
  const addShow = ref(false);
  const addModel = ref();

  const openAdd = () => {
    addShow.value = true;
    addForm.value = generateDataModel();
  };

  const handleCheck = (done) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    addModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          if (addForm.value.dictId) {
            updateDictType(addForm.value).then((res) => {
              if (res.code == '200') {
                Message.success({
                  content: res.message,
                });
                done(true);
                reset();
              } else {
                done(false);
              }
            });
          } else {
            addDictType(addForm.value).then((res) => {
              if (res.code == '200') {
                Message.success({
                  content: res.message,
                });
                done(true);
                reset();
              } else {
                done(false);
              }
            });
          }
        } else {
          done(false);
        }
      }
    );
  };

  const openEdit = (item) => {
    addForm.value = Object.assign({}, item);
    addShow.value = true;
  };

  const handleCancel = () => {
    addShow.value = false;
  };
  const openDelete = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除吗？',
      onOk() {
        deleteDictType({
          id: item.dictTypeId,
        }).then((res) => {
          if (res.code == '200') {
            Message.success({
              content: res.message,
            });
            fetchData();
          }
        });
      },
    });
  };

  const columns = computed<TableColumnData[]>(() => [
    {
      title: '字典名称',
      dataIndex: 'dictName',
      align: 'center',
    },
    {
      title: '字典类型',
      dataIndex: 'dictType',
      align: 'center',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center',
    },

    {
      title: '操作',
      dataIndex: 'option',
      slotName: 'option',
      align: 'center',
    },
  ]);

  const generateFormModel = () => {
    return {
      dictName: '',
      dictType: '',
    };
  };

  const formModel = ref(generateFormModel());
  const renderData = ref([]);

  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });

  const fetchData = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: pagination.current,
        ...pagination,
        ...formModel.value,
      };
      dictTypeList(data).then((res) => {
        renderData.value = res.data.list;
        pagination.total = res.data.total;
        pagination.current = res.data.current;
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };

  fetchData();
  const reset = () => {
    formModel.value = generateFormModel();
    fetchData();
  };
</script>
